package hlhj.fhp.newslib.fragments

import android.content.Intent
import android.content.res.Resources
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.ShapeDrawable
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.text.TextUtils
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.lzy.okgo.OkGo
import com.lzy.okgo.cache.CacheMode
import com.lzy.okgo.model.Response
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.tenma.ventures.bean.TMUser
import com.tenma.ventures.bean.utils.TMSharedPUtil
import hlhj.fhp.newslib.BaseFgm
import hlhj.fhp.newslib.R
import hlhj.fhp.newslib.activitys.ChooseAty
import hlhj.fhp.newslib.activitys.SearchAty
import hlhj.fhp.newslib.adapters.FragmentAdp
import hlhj.fhp.newslib.customview.GoLoginDialog
import hlhj.fhp.newslib.javabean.ColumBean
import hlhj.fhp.newslib.javabean.LogoBean
import hlhj.fhp.newslib.javabean.TabBean
import hlhj.fhp.newslib.network.Apis
import hlhj.fhp.newslib.network.CustomAction
import hlhj.fhp.newslib.network.LoadingAction
import hlhj.fhp.newslib.network.Urls
import hlhj.fhp.newslib.utils.GlideUtil
import hlhj.fhp.newslib.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_main_aty.*
import kotlinx.android.synthetic.main.activity_main_aty.view.*
import kotlinx.android.synthetic.main.tab_my_item.view.*
import java.lang.reflect.Field
import java.util.ArrayList

/**
 * Created by Administrator on 2018\6\28 0028.
 */
class MainFgm:BaseFgm() {
    private val tabStrs= ArrayList<String>()
    private val fgmList= ArrayList<Fragment>()
    private lateinit var fgmPagerAdp: FragmentAdp
    private lateinit var recommendFgm: Fragment
    private val tabs= ArrayList<TabBean>()
    private val gochoose=1
    override fun initListener() {
        rootView.btMore.setOnClickListener {
            if (TMSharedPUtil.getTMToken(context).isEmpty()){
                GoLoginDialog(context!!).show()
                return@setOnClickListener
            }
            val intent = Intent(context, ChooseAty::class.java)
            activity!!.startActivityFromFragment(this,intent,gochoose)
        }
        rootView.btGoSearch.setOnClickListener {
            val intent = Intent(context, SearchAty::class.java)
            startActivity(intent)
        }
    }

    override fun onPause() {
        super.onPause()
        Log.e("fhp","pause")
        GSYVideoManager.releaseAllVideos()
    }

    override fun onResume() {
        super.onResume()
        getLogo()
        Log.e("fhp","resume")
    }

    override fun onStop() {
        Log.e("fhp","stop")
        super.onStop()
    }
    override fun onDestroy() {
        super.onDestroy()
        Log.e("fhp","destory")
        GSYVideoManager.releaseAllVideos()
    }
    override fun initView() {
        /*初始化OKGO*/
        OkGo.getInstance().init(activity?.application)

        ToastUtil.init(context)
        rootView.viewPager.offscreenPageLimit=10
        rootView.tabLayout.tabMode= TabLayout.MODE_SCROLLABLE

        if (null!=rootView.loBack){
            if (null!= TMSharedPUtil.getTMThemeColor(context)&& TMSharedPUtil.getTMThemeColor(context).length>0){
                rootView.loBack.setBackgroundColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(context)))
                val gradientDrawable = rootView.btBack.background as GradientDrawable
                gradientDrawable.setColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(context)))
                rootView.background=gradientDrawable
            }
        }
        disPatchColumn()
    }
    fun disPatchColumn(){
        /*列表*/
        val tmUser = TMSharedPUtil.getTMUser(context)
        if (tmUser==null){
            Apis.getColumnList(null)
                    .doOnSubscribe(LoadingAction(context!!))
                    .subscribe(object : CustomAction<Response<ColumBean>> {
                        override fun onResult(t: Response<ColumBean>) {
                            loadingDialog.dismiss()
                            val columBean = t.body()
                            for (i in 0..columBean.data.defaultX.size-1){
                                val tabBean = TabBean()
                                tabBean.id=columBean.data.defaultX[i].id
                                tabBean.name=columBean.data.defaultX[i].category_name
                                tabs.add(tabBean)
                            }
                            initTab()
                        }
                    })
            return
        }
        Apis.getColumnList(tmUser.member_id)
                .doOnSubscribe(LoadingAction(context!!))
                .subscribe(object : CustomAction<Response<ColumBean>> {
                    override fun onResult(t: Response<ColumBean>) {
                        loadingDialog.dismiss()
                        val columBean = t.body()
                        for (i in 0..columBean.data.defaultX.size-1){
                            val tabBean = TabBean()
                            tabBean.id=columBean.data.defaultX[i].id
                            tabBean.name=columBean.data.defaultX[i].category_name
                            tabs.add(tabBean)
                        }
                        initTab()
                    }
                })
        /*logo*/
//        getLogo()
    }

    private fun getLogo() {
        Apis.getLogo()
                .doOnSubscribe {
                }.subscribe(object : CustomAction<Response<LogoBean>> {
            override fun onResult(t: Response<LogoBean>) {
                val logoBean = t.body()
                rootView.loSearch.visibility = View.VISIBLE
                if (null != logoBean.data && !logoBean.data.equals("")) {
                    if (!TextUtils.isEmpty(logoBean.data.search_log)){
                        if (logoBean.data.search_log.contains("http")){
                            Glide.with(context!!).load(logoBean.data.search_log).into(imgSearch)
                        }else{
                            Glide.with(context!!).load(Urls.Base_URL+logoBean.data.search_log).into(imgSearch)
                        }
                    }
                    if (logoBean.data.logo == null || logoBean.data.logo.equals("")) {
                        rootView.imgLogo.visibility = View.GONE
                    } else {
                        rootView.imgLogo.visibility = View.VISIBLE
                        Glide.with(context!!).load(logoBean.data.logo).apply(GlideUtil.loadIMGOption()).into(rootView.imgLogo)
                    }
                    if (logoBean.data.personal == 1) {
                        rootView.btSelf.visibility = View.VISIBLE
                        if (!TextUtils.isEmpty(TMSharedPUtil.getTMUser(context).head_pic)) {
                            if (TMSharedPUtil.getTMUser(context).head_pic.contains("http")) {
                                Glide.with(context!!).load(TMSharedPUtil.getTMUser(context).head_pic).into(rootView.btSelf)
                            } else {
                                Glide.with(context!!).load(Urls.Base_URL + "/" + TMSharedPUtil.getTMUser(context).head_pic).into(rootView.btSelf)
                            }
                        } else {
                            val avatar = logoBean.data.avatar
                            if (avatar.contains("http")) {
                                Glide.with(context!!).load(avatar).into(rootView.btSelf)
                            } else {
                                Glide.with(context!!).load(Urls.Base_URL + "/" + avatar).into(rootView.btSelf)
                            }
                        }
                        rootView.btSelf.setOnClickListener {
                            val intent = Intent(context!!.packageName + ".usercenter.UCMain")
                            startActivity(intent)
                        }
                    } else {
                        rootView.btSelf.visibility = View.GONE
                    }

                }
            }
        })
    }

    private fun initTab(){
        for (i in 0..tabs.size-1){
            val tab = rootView.tabLayout.newTab()
            val tabLay = LayoutInflater.from(context).inflate(R.layout.tab_my_item, null)
            tabLay.tabText.text=tabs[i].name
            tab.setCustomView(tabLay)
//            tab.setText(tabs[i].name)
            rootView.tabLayout.addTab(tab)
            Log.e("fhp","看下但因的Id${tabs[i].id}在看下大小${fgmList.size}")
            val instence = RecommendFgm.getInstence(tabs[i].id,tabs[i].name)
            fgmList.add(instence)
        }
        if (null!= TMSharedPUtil.getTMThemeColor(context)&& TMSharedPUtil.getTMThemeColor(context).length>0){
            rootView.tabLayout.setSelectedTabIndicatorColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(context)))
            rootView.tabLayout.setTabTextColors(Color.parseColor("#333333"),Color.parseColor(TMSharedPUtil.getTMThemeColor(context)))
        }
        fgmPagerAdp=FragmentAdp(childFragmentManager,fgmList)
        rootView.viewPager.adapter=fgmPagerAdp
//        rootView.tabLayout.setupWithViewPager(rootView.viewPager)
        rootView.tabLayout.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }
            override fun onTabSelected(tab: TabLayout.Tab?) {
                doTab(tab?.position!!)
                rootView.viewPager.currentItem=tab?.position
            }
        })
        rootView.viewPager.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                GSYVideoManager.releaseAllVideos()
            }

            override fun onPageSelected(position: Int) {
                doTab(position)
                rootView.tabLayout.getTabAt(position)?.select()
            }
        })
        rootView.tabLayout.getTabAt(0)?.select()
        /*设置tablayout*/
//        setIndicator(rootView.tabLayout,0f,0f)
        val tabAt = rootView?.tabLayout.getTabAt(0)
        val tabView = tabAt?.customView
        tabView?.tabText?.setBackgroundResource(R.drawable.tab_select_border)

        val gradientDrawable2 = tabView?.tabText?.background as GradientDrawable
        if (null!= TMSharedPUtil.getTMThemeColor(context)&& TMSharedPUtil.getTMThemeColor(context).length>0){
            gradientDrawable2.setStroke(2,Color.parseColor( TMSharedPUtil.getTMThemeColor(context)))
            tabView?.tabText?.setTextColor(Color.parseColor( TMSharedPUtil.getTMThemeColor(context)))
        }else{
            gradientDrawable2.setStroke(2,Color.parseColor("#d81e07"))
            tabView?.tabText?.setTextColor(Color.parseColor( "#d81e07"))

        }
        tabView?.tabText?.background=gradientDrawable2
    }
    private fun doTab(position:Int) {
        for (i in 0 until rootView.tabLayout.tabCount) {
            val tabAt = rootView.tabLayout.getTabAt(i)
            val tabView = tabAt?.customView
            if (i == position) {
                tabView?.tabText?.setBackgroundResource(R.drawable.tab_select_border)
                val gradientDrawable2 = tabView?.tabText?.background as GradientDrawable
                if (null!= TMSharedPUtil.getTMThemeColor(context)&& TMSharedPUtil.getTMThemeColor(context).length>0){
                    gradientDrawable2.setStroke(2,Color.parseColor( TMSharedPUtil.getTMThemeColor(context)))

                }else{
                    gradientDrawable2.setStroke(2,Color.parseColor("#d81e07"))
                }
                    tabView?.tabText?.background=gradientDrawable2
                Log.e("fhpp", "设置颜色失效了？")
                if (null!= TMSharedPUtil.getTMThemeColor(context)&& TMSharedPUtil.getTMThemeColor(context).length>0){
                    tabView?.tabText!!.setTextColor(Color.parseColor(TMSharedPUtil.getTMThemeColor(context)))
                    val gradientDrawable = tabView?.tabText?.background as GradientDrawable
                    gradientDrawable.setStroke(2,Color.parseColor(TMSharedPUtil.getTMThemeColor(context)))
                    tabView?.tabText?.background=gradientDrawable
                }else{
                    tabView?.tabText!!.setTextColor(Color.parseColor("#d81e07"))
                    val gradientDrawable = tabView?.tabText?.background as GradientDrawable
                    gradientDrawable.setStroke(2,Color.parseColor("#d81e07"))
                    tabView?.tabText?.background=gradientDrawable
                }
            } else {
                tabView?.tabText!!.setTextColor(Color.parseColor("#333333"))
                tabView?.tabText?.background=null
            }
        }
    }

    override fun getContentId(): Int {
        return  R.layout.activity_main_aty
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.e("fhp","到回调了")
        if (resultCode!=-1)return
        if (requestCode==gochoose){
            Log.e("fhp","到回调了2")
            rootView.tabLayout.removeAllTabs()
            tabs.clear()
            fgmList.clear()
     /*       for (i in 0..fgmList.size-1){
                fgmList[i].onDestroy()
            }*/
         /*
            fgmPagerAdp.notifyDataSetChanged()*/
            Apis.getColumnList(TMSharedPUtil.getTMUser(context).member_id)
                    .doOnSubscribe(LoadingAction(context!!))
                    .subscribe(object : CustomAction<Response<ColumBean>> {
                        override fun onResult(t: Response<ColumBean>) {
                            loadingDialog.dismiss()
                            val columBean = t.body()
                            for (i in 0..columBean.data.defaultX.size-1){
                                val tabBean = TabBean()
                                tabBean.id=columBean.data.defaultX[i].id
                                tabBean.name=columBean.data.defaultX[i].category_name
                                tabs.add(tabBean)
                            }
                            initTab()
                        }
                    })
        }
    }


}